<template>
  <div id="IndexModelMap-map" style="width: 100%; height: 658px"></div>
  <div id="IndexModelMap-mapDiv" class="ol-popup">
    <!-- 显示控件 -->
    <div id="IndexModelMap-setDivPosition" class="init-setDivPosition">
      <!-- 切换卫星和街道地图 -->
			<p @click="switchMap" class="init-setDivPosition-selected">
				<template v-if="switchMapBool==false">
					<img src="@/assets/map/image/weixing-b.png" title="切换卫星地图"><br/><span>卫星图</span>
				</template>
				<template v-else>
					<img src="@/assets/map/image/jiedao-b.png" title="切换街道地图"><br/><span>街道图</span>
				</template>
			</p>
			<!-- 返回主界面 -->
			<p @click="zoomDefaultPosition" :class="{ 'init-setDivPosition-selected': zoomDefaultPositionBool==true }">
				<img src="@/assets/map/image/newImage/home.png" title="返回主界面"><br/><span>主界面</span>
			</p>
			<!-- 显示工具箱 -->
			<p @click="showHideToolsBoxDiv" :class="{ 'init-setDivPosition-selected': showHideToolsBox==false }">
				<template v-if="showHideToolsBox">
					<img src="@/assets/map/image/tools.png" title="打开工具箱"><br/><span>工具箱</span>
				</template>
				<template v-else>
					<img src="@/assets/map/image/tools.png" title="关闭工具箱"><br/><span>工具箱</span>
				</template>
			</p>
      <!-- 图层数据 -->
      <p v-if="dataLayerVisible" @click="showDataLayer" :class="{ 'init-setDivPosition-selected': dataLayerBool == true }">
        <img src="@/assets/map/image/icon-数据图层.png" title="坡度数据" /><br /><span>数据图层</span>
      </p>
      <!-- 评估结果 -->
      <p v-if="estimateResultVisible" @click="showEstimateResult" :class="{ 'init-setDivPosition-selected': estimateResultBool == true }">
        <img src="@/assets/map/image/icon-评估结果.png" title="评估结果" /><br /><span>评估结果</span>
      </p>
      <!-- 生成图件 -->
      <p v-if="imgcreateVisible" @click="showImgcreate" :class="{ 'init-setDivPosition-selected': createImagBool == true }" >
        <img src="@/assets/map/image/icon-图件生成.png" title="生成图件" /><br /><span>生成图件</span>
      </p>
      <!-- 返回评估页面 -->
      <p @click="returnEstimateButton" :class="{ 'init-setDivPosition-selected': returnEstimateBool == true }" >
        <img src="@/assets/map/image/icon-返回评估页面.png" title="返回评估页面" /><br />
        <span style="font-size: 12px; width: 72px; border: 0">返回评估页面</span
        >
      </p>
    </div>
    <!-- 工具箱 -->
		<div id="IndexModelMap-ToolsBoxDiv" class="init-ToolsBoxDiv">
			<p @click="measureToolBox" :class="{ 'init-setDivPosition-selected': showHideMeasureTool==false }">
				<template v-if="showHideMeasureTool">
					<img title="开启测量工具" src="@/assets/map/image/cel.png"><br/><span>测量</span>
				</template>
				<template v-else>
					<img title="关闭测量工具" src="@/assets/map/image/cel.png"><br/><span>测量</span>
				</template>
			</p>
			<p @click="positionToolBox" :class="{ 'init-setDivPosition-selected': showHidePositionTool==false }">
        <template v-if="showHidePositionTool">
          <img title="开启定位工具" src="@/assets/map/image/dingw.png"><br/><span style="border:0;">定位</span>
        </template>
        <template v-else>
          <img title="关闭定位工具" src="@/assets/map/image/dingw.png"><br/><span style="border:0;">定位</span>
        </template>
      </p>
		</div>
    <!-- 所有工具 -->
    <div id="IndexModelMap-AllToolsDiv" class="init-AllToolsDiv">
      <!-- 测量工具 -->
      <div id="IndexModelMap-MeasureToolsDiv" class="init-AllToolsDivFloat">
        <p @click="measureDistance" :class="{ 'init-setDivPosition-selected': measureDistanceBool==false }">
          <template v-if="measureDistanceBool">
            <img src="@/assets/map/image/jul.png" title="测量距离（在地图上单击鼠标左键绘制折线，双击完成测量）"><br/><span>测量距离</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/jul.png" title="测量距离（在地图上单击鼠标左键绘制折线，双击完成测量）"><br/><span>测量距离</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="measureArea" :class="{ 'init-setDivPosition-selected': measureAreaBool==false }">
          <template v-if="measureAreaBool">
            <img src="@/assets/map/image/mianj.png" title="测量面积（在地图上单击鼠标左键绘制多边形，双击完成测量）"><br/><span>测量面积</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/mianj.png" title="测量面积（在地图上单击鼠标左键绘制多边形，双击完成测量）"><br/><span>测量面积</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="stopMeasure" :class="{ 'init-setDivPosition-selected': stopMeasureBool==false }">
          <template v-if="stopMeasureBool">
            <img src="@/assets/map/image/jshz.png" title="取消测量距离或测量面积操作"><br/><span>结束测量</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/jshz.png" title="取消测量距离或测量面积操作"><br/><span>结束测量</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="clearMeasure" :class="{ 'init-setDivPosition-selected': clearMeasureBool==false }">
          <template v-if="clearMeasureBool">
            <img src="@/assets/map/image/qux.png" title="清空全部测量结果"><br/><span>清空结果</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/qux.png" title="清空全部测量结果"><br/><span>清空结果</span>
          </template>
        </p>
      </div>
      <!-- 定位工具 -->
      <div id="IndexModelMap-MousePositionDiv">
        <span><img class="init-jingd" src="@/assets/map/image/jingd.png" title="鼠标左键在地图上点击位置的经度值"></span>
        <input id="IndexModelMap-MousePositionLon" type="text" value="">
        <span><img class="init-weid" src="@/assets/map/image/weid.png" title="鼠标左键在地图上点击位置的纬度值"></span>
        <input id="IndexModelMap-MousePositionLat" type="text" value="">
        <p @click="clearPosition" :class="{ 'init-setDivPosition-selected': clearPositionBool==false }">
          <template v-if="clearPositionBool">
            <img src="@/assets/map/image/qux.png" title="清空全部定位点图标"><br/><span>清空结果</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/qux.png" title="清空全部定位点图标"><br/><span>清空结果</span>
          </template>
        </p>
        <p class="init-AllToolsDiv-split"></p>
        <p @click="addPosition" :class="{ 'init-setDivPosition-selected': addPositionBool==false }">
          <template v-if="addPositionBool">
            <img src="@/assets/map/image/dingwd.png" title="根据经纬度值在地图上添加定位点图标"><br/><span>添加定位点</span>
          </template>
          <template v-else>
            <img src="@/assets/map/image/dingwd.png" title="根据经纬度值在地图上添加定位点图标"><br/><span>添加定位点</span>
          </template>
        </p>
      </div>
    </div>
    <div id="IndexModelMap-popup" class="new-ol-popup" style="display:none;">
      <div id="IndexModelMap-popup-content"></div>
    </div>
  </div>
</template>
<script>
import Map from "ol/Map";
import View from "ol/View";
import VectorLayer from "ol/layer/Vector";
import WKT from "ol/format/WKT";
import { Cluster, Vector as VectorSource, XYZ } from "ol/source";
import { boundingExtent } from "ol/extent";
import { iServerHttp } from "@/map/projMap.js";
import { detailTask } from "@/api/taskmanage/task";
import {MapService,GetFeaturesByGeometryParameters,Util,GridCellInfosService,GetGridCellInfosParameters, QueryBySQLParameters, QueryService, FeatureService, GetFeaturesBySQLParameters, } from "@supermap/iclient-ol";
import { getProjection,getRESTLayer, getTiandituVecMap, getTiandituVecText,getTiandituImgMap, getVectorTileLayer, getTiandituImgText } from "@/map/projMap.js";
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Overlay from 'ol/Overlay';
import {Select, Draw, Modify, Snap, Translate} from 'ol/interaction';
import {unByKey} from 'ol/Observable';
import CircleDraw from 'ol/geom/Circle';
import Polygon from 'ol/geom/Polygon';
import {fromCircle} from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import {getArea, getLength} from 'ol/sphere';
import {Fill, Stroke, Style, Icon, Circle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
export default {
  name: "Map",
  props: {
    taskRegion: {
      //烈度面板选择的值 || 超越概率选择的值
      type: String,
      required: true,
      default: "",
    },
    takId: {
      // 任务ID
      type: String,
      required: true,
      default: "",
    },
    slopeVersionId: {
      type: String,
      required: true,
      default: "",
    },
    lithologyVersion: {
      type: String,
      required: true,
      default: "",
    },
    estimateTool: {
      // 初始化打开评估结果
      type: Boolean,
      required: true,
      default: false,
    },
    addLayerData: {
      // 添加图层列表数据
      type: Object,
      required: true,
      default: {},
    },
    estimateModelType: {
      // 模型的类型 层次/指数/逻辑斯蒂/黄土/Newmark
      type: String,
      required: true,
      default: "",
    },
    sqlObj: {
      type: Object,
      required: true,
      default: {}
    },
    taskGoem: {
      type: String,
      required: true,
      default: ''
    }
  },
  emits: [
    "mapLoading",
    "showEvaluateResultSelect",
    "closeLegend",
    "returnSetPage",
    "isDataLayer",
    'showImgcreate',
    "getLegendHtml",
  ],
  data() {
    return {
      str: "IndexModelMap",
      map: null,
      center: [105, 34],
      zoom: 4,
      layer1: null,
      layer2: null,
      layer3: null,
      layer4: null,
      source: null,// 矢量绘制图层
      measureSource: null,// 测量结果图层
      switchMapBool: false, // 卫星图
      zoomDefaultPositionBool: true,// 返回主界面
      showHideToolsBox: true,// 工具箱
      showHideMeasureTool:true,//显示|隐藏测量工具
      showHidePositionTool: true,// 定位工具
      measureDistanceBool: true,
      measureAreaBool: true,
      stopMeasureBool: true,
			clearMeasureBool: true,
      clearPositionBool: true,
			addPositionBool: true,
      helpTooltipElement:null,
      helpTooltip:null,
      measureTooltipElement:null,
      measureTooltip:null,
      measure: null,
      overlay: null,
      measureTooltipArray:[],//全部测量结果Overlay数组
      mapLoadingBool: false,
      dataLayerBool: false,
      dataLayerVisible: false, // 是否展示数据图层
      slopeDataBool: false,
      slopeDataVisible: false, // 是否展示坡度数据
      formationlithologyVisible: false, // 是否显示地层岩性
      formationlithologyBool: true,
      engineeringGeologyVisible: false, // 工程地质岩组归并结果
      estimateResultBool: false,
      estimateResultVisible: false, // 是否显示评估结果
      imgcreateVisible: false, // 是否显示生成图件
      createImagBool: false,
      returnEstimateBool: false,
      taskRegionData: "",
      evaluateResultLayer: null, //评估结果显示图层
      lengendData: [], // 图例数据
      allRestVectorLayerArray: [], //全部超图图层数组
      taskID: "", // 任务id
      html: '',
      sGLayerUrl: ''
    };
  },
  watch: {
    taskRegion: {
      handler: function (newVal, oldVal) {
        if (newVal != oldVal && newVal != null && newVal != "") {
          console.log(newVal)
          this.taskRegionData = newVal;
          // this.drawTaskPonloy()
          this.selectIServerRest();
        }
      },
      immediate: true,
    },
    takId: {
      handler: function (newVal, olaVal) {
        this.taskID = newVal;
      },
      immediate: true,
    },
    slopeVersionId: {
      handler: function (newVal, oldVal) {},
      immediate: true,
    },
    lithologyVersion: {
      handler: function (newVal, oldVal) {},
      immediate: true,
    },
    estimateTool: {
      handler: function (newVal, oldVal) {
        this.estimateResultBool = newVal;
      },
      immediate: true,
    },
    addLayerData: {
      // 添加与移除数据图层
      handler: function (newVal, oldVal) {
        this.dataLayer = newVal;
        if (newVal != oldVal) {
          this.addIserverLayer(this.dataLayer);
        }
      },
      immediate: true,
    },
    estimateModelType: {
      // 根据模型类型 控制按钮显示
      handler: function (newVal, oldVal) {
        if (newVal == "1" || newVal == "2") { // 标贯法(饱和砂土或粉土1/饱和黄土2) 
          this.dataLayerVisible = false; // 数据图层工具
          this.engineeringGeologyVisible = true; // 工程地质岩组归并结果工具
          this.slopeDataVisible = false; // 坡度数据工具
          this.estimateResultVisible = true; // 评估结果工具
          this.formationlithologyVisible = false; // 地层岩性工具
          this.imgcreateVisible = true; //生成图件工具
        } else if (newVal == "3" || newVal == "4") { // 液化指数法(饱和砂土或粉土3/饱和黄土4)
          this.dataLayerVisible = false;
          this.engineeringGeologyVisible = false;
          this.slopeDataVisible = true;
          this.estimateResultVisible = true;
          this.formationlithologyVisible = false;
          this.imgcreateVisible = true;
        } else { // 层次分析法5
          this.dataLayerVisible = true;
          this.engineeringGeologyVisible = false;
          this.slopeDataVisible = true;
          this.estimateResultVisible = true;
          this.formationlithologyVisible = false;
          this.imgcreateVisible = true;
        }
      },
      immediate: true,
    },
    sqlObj: {
      handler: function(newVal, oldVal) {

      },
      immediate: true
    },
    taskGoem: {
      handler: function(newVal, oldVal){
        if(newVal != '') {
          this.drawTaskGeom(newVal)
        }
      },
      immediate: true
    }
  },
  mounted() {
    let that = this;
    this.$nextTick(function () {
      setTimeout(() => {
        // 初始化地图
        that.initMap();
      }, 200);
    });
  },
  methods: {
    initMap() {
      let that = this
      let targetMap = document.getElementById(this.str + "-map");
      // 清空targetMap
      targetMap.innerHTML = "";
      this.mapLoadingBool = true;
      // 获取地图div的高度
      this.autodivheight();
      // 浏览器窗口发生变化时同时变化DIV高度
      window.onresize = this.autodivheight();
      if (this.map) {
        //避免地图重复加载
        return;
      }
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      console.log(this.center)
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution: true, //缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: "EPSG:4490",
        }),
      });
      this.layer1 = getTiandituVecMap();
      this.map.addLayer(this.layer1);
      this.layer2 = getTiandituVecText();
      this.map.addLayer(this.layer2);
      this.layer1.setZIndex(0);
      this.layer2.setZIndex(0);
      //评估结果显示图层
      this.evaluateResultLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false,
        }),
        projection: "EPSG:4490",
      });
      this.map.addLayer(this.evaluateResultLayer);
      this.evaluateResultLayer.setZIndex(7);
      //矢量绘制图层
      this.source = new VectorSource({
        wrapX: false
      });
      let vectorLayer = new VectorLayer({
        source: that.source,
        projection: 'EPSG:4490'
      });
      this.map.addLayer(vectorLayer);
      vectorLayer.setZIndex(2);
      //测量结果图层
      this.measureSource = new VectorSource({
        wrapX: false
      });
      let measureLayer = new VectorLayer({
        source: that.measureSource,
        projection: 'EPSG:4490'
      });
      this.map.addLayer(measureLayer);
      //地图弹窗
      let container = document.getElementById(this.str+'-popup');
      this.overlay = new Overlay(({
        element: container,
        autoPan: true,
        autoPanAnimation: {
          duration: 250
        }
      }));
      this.map.addOverlay(this.overlay);
      this.overlay.setPosition(undefined);
      // this.closePopupContent()
      this.map.on('click', function(event){
        let coordinate = that.map.getEventCoordinate(event.originalEvent)
        if (that.showHidePositionTool == false) {
          document.getElementById(that.str + '-MousePositionLon').value = coordinate[0]
          document.getElementById(that.str + '-MousePositionLat').value = coordinate[1]
        }
        if(that.estimateResultBool) {
          let zoom = that.map.getView().getZoom();
          let temp = Math.pow(2,(18 - zoom));
          //点生成圆多边形
          let meter = 3 * temp;//米
          let degree = meter / (Math.PI * 2 * 6378137 / 360);
          let circle = new CircleDraw(coordinate, degree); // 用圆心和半径确定一个圆
          let polygon = new fromCircle(circle) // 得到一个多边形
          let extent = new Feature({
            geometry: polygon
          });
          let center = extent.getGeometry()
          let type = that.estimateModelType;
          let dataNamme
          if(type == '1' || type == '2' || type == '3' || type == '4') {
            dataNamme = 'fxfzdzzh:dzzh_result_sand_liquefaction'
            let geometryParam = new GetFeaturesByGeometryParameters({
              datasetNames: [dataNamme],
              geometry: center,
              spatialQueryMode: "INTERSECT",
            });
            let url = iServerHttp() + '/iserver/services/data-fxfzdzzh/rest/data'
            //向服务器发送请求，并对返回的结果进行处理
            new FeatureService(url).getFeaturesByGeometry(geometryParam, function (serviceResult) {
              //获取返回的features数据
              if (serviceResult.result != undefined && serviceResult.result.features.features.length != 0) {
                var result = serviceResult.result.features.features[0].properties;
                that.addPopupContent(result,coordinate,'point')
              }else if(dataNamme == 'fxfzdzzh:dzzh_result_sand_liquefaction') {
                if(type == '1' || type == '2') {
                  geometryParam = new GetFeaturesByGeometryParameters({
                    datasetNames: ['fxfzdzzh:dzzh_sand_liquefaction_polygon_evaluate_result1'],
                    geometry: center,
                    spatialQueryMode: "INTERSECT",
                  });
                }else if(type == '3' || type == '4') {
                  geometryParam = new GetFeaturesByGeometryParameters({
                    datasetNames: ['fxfzdzzh:dzzh_sand_liquefaction_polygon_evaluate_result2'],
                    geometry: center,
                    spatialQueryMode: "INTERSECT",
                  });
                }
                new FeatureService(url).getFeaturesByGeometry(geometryParam, function (serviceResult) {
                  if (serviceResult.result != undefined && serviceResult.result.features.features.length != 0) {
                    var result = serviceResult.result.features.features[0].properties;
                    that.addPopupContent(result,coordinate,'polygon')
                  }else{
                    that.closePopupContent()
                  }
                })
              }else {
                that.closePopupContent()
              }
            });
          }else {
            that.getTifValueInfo(coordinate)
          }
        }else{
          that.closePopupContent()
        }
      })
    },
    getTifValueInfo(lonlat){//根据经纬度获取栅格值
      let that = this;
      let tifUrl = iServerHttp()+"/iserver/services/data-dzzhTifCount/rest/data";
      let getGridCellInfosParam = new GetGridCellInfosParameters({
        dataSourceName: "dzzhTifCount",
        datasetName: that.taskRegionData,
        // datasetName: 'gc1696903447872',
        X: lonlat[0],
        Y: lonlat[1]
      });
      new GridCellInfosService(tifUrl).getGridCellInfos(getGridCellInfosParam, function (serviceResult) {
        console.log(serviceResult);
        let result = serviceResult.result
        if (result == undefined) {
          that.closePopupContent()
        }else {
          let innerHTML = "行: " + result.row + "<br>";
          innerHTML += "列: " + result.column + "<br>";
          innerHTML += "值: " + result.value + "<br>";
          that.setPopupContent(innerHTML);
          that.overlay.setPosition(lonlat);
        }
      })
    },
    drawTaskGeom(geom) {
      let feature = new WKT().readFeature(geom)
      let style = this.getPolyonStyle('orange')
      feature.setStyle(style)
      this.evaluateResultLayer.getSource().addFeature(feature)
    },
    addPopupContent(result,coordinate,type) {
      let innerHTML
      let isLiquefying
      let typeLayer = that.estimateModelType;
      if(typeLayer == '1' || typeLayer == '2') {
        if (type == 'point') {
          isLiquefying = result.DRILL_LIQUEFACTION_DIFFERENTIATE == '1' ? '不液化' : '液化'
          innerHTML = "钻孔编号: " + result.DRILL_CODE + "<br>";
          innerHTML += '钻孔液化判别结果：' + isLiquefying + '<br>'
        }else if(type == 'polygon') {
          isLiquefying = result.VALUE == '1' ? '不液化' : '液化'
          innerHTML += '液化判别结果：' + isLiquefying + '<br>'
        }
      }else if(type == '3' || type == '4') {
        if (type == 'point') {
          innerHTML = "钻孔编号: " + result.DRILL_CODE + "<br>";
          innerHTML += "钻孔液化指数IE: " + result.DEI + "<br>";
          innerHTML += '钻孔液化等级' + result.SAND_LEVEL + "<br>";
        }else if(type == 'polygon') {
          innerHTML += '液化等级' + result.SAND_LEVEL + "<br>";
        }
      }else{

      }
      this.setPopupContent(innerHTML);
      this.overlay.setPosition(coordinate);
    },
    closePopupContent() {
      document.getElementById(this.str+"-popup").style.display = "none";
    },
    setPopupContent(html){//设置弹窗内容
      document.getElementById(this.str+'-popup-content').innerHTML = html;
      //显示弹出窗口
      document.getElementById(this.str+"-popup").style.display="block";
    },
    showImgcreate() {
      // 生成图件按钮
      if (this.createImagBool) {
        this.createImagBool = false;
        this.selectTemplentId(false)
      } else {
        this.createImagBool = true;
        this.selectTemplentId(true)
      }
    },
    selectTemplentId(flag) {
      let params = {
        bool: flag,
        list: this.allRestVectorLayerArray
      }
      this.$emit("showImgcreate",params);
    },
    showSlopeData() {
      // 坡度数据按钮
      // 版本号
      getAttachById(this.slopeVersionId).then((res) => {
        let tifName = res.data.attachName.substring(
          0,
          res.data.attachName.length - 4
        );
        let params = {
          data: {
            id: "",
            url:
              iServerHttp() + "/iserver/services/map-dzzhTifFile/rest/maps/" +
              tifName,
          },
          layerState: !this.slopeDataBool,
        };
        if (this.slopeDataBool) {
          this.slopeDataBool = false;
          this.addIserverLayer(params);
        } else {
          this.slopeDataBool = true;
          let type = this.estimateModelType;
          if (type == "指数模型") {
            this.addIserverLayer(params);
          } else if (type == "逻辑斯蒂模型") {
            this.addIserverLayer(params);
          }
        }
      });
    },
    showEstimateResult() {
      // 评估结果按钮
      if (this.estimateResultBool) {
        this.closePopupContent()
        this.estimateResultBool = false;
        if(this.estimateModelType != '7') {
          this.deleteRestMapTempLayersSet();
        }else{
          this.addIserverLayerSG(this.sGLayerUrl)
        }
        this.$emit("showEvaluateResultSelect", false);
      } else {
        this.estimateResultBool = true;
        this.$emit("showEvaluateResultSelect", true);
      }
    },
    showDataLayer() {
      // 图层数据按钮
      if (this.dataLayerBool) {
        this.dataLayerBool = false;
        this.$emit("isDataLayer", false);
      } else {
        this.dataLayerBool = true;
        this.$emit("isDataLayer", true);
      }
    },
    addIserverLayer(value) {
      // 添加超图服务显示到地图
      let that = this;
      console.log(value.data);
      if (value.data) {
        if (value.layerState) {
          // 添加数据图层
          let mapService = new MapService(value.data.url); //根据超图矢量瓦片图层获取图层信息
          let layer;
          mapService.getMapInfo(function (serviceResult) {
            if (serviceResult.result != undefined) {
              let mapJSONObj = serviceResult.result;
              let bounds = mapJSONObj.bounds;
              let left = bounds.left;
              let bottom = bounds.bottom;
              let right = bounds.right;
              let top = bounds.top;
              let origin = [left, top]; //左上角
              let extent = [left, bottom, right, top]; //图层范围
              layer = getRESTLayer(value.data.url, "", origin, extent, "", 10);
              that.map.addLayer(layer);
              that.map.getView().fit(extent, { padding: [100, 100, 100, 100] });
            }
          });
        } else {
          // 移除数据图层
          let layers = that.map.getLayers();
          let index = -1;
          for (let i = 0; i < layers.array_.length; i++) {
            if (layers.array_[i].values_.source.options) {
              if (
                value.data.url == layers.array_[i].values_.source.options.url
              ) {
                index = i;
              }
            }
          }
          that.map.removeLayer(layers.array_[index]);
        }
      }
    },
    selectIServerRest() {
      // 添加评估结果图层
      let type = this.estimateModelType;
      let url;
      if (type == "1" || type == "2") {
        this.html = ''
        if(this.sqlObj.liquefactionGroundWaterDepth == '0') {
          this.deleteIserverLayer(
            iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_result_sand_liquefaction@fxfzdzzh",
            "earthquake_acceleration = '" + this.sqlObj.earthquakeAcceleration +
            "' and liquefaction_ground_water_depth = '" + this.sqlObj.liquefactionGroundWaterDepth + "' and task_id = '"
            + this.taskID + "' and algorithm_type == '1' and dmsl_id = '" + this.sqlObj.dmslId + "'",'point'
          )
        }else{
          this.deleteIserverLayer(
            iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_result_sand_liquefaction@fxfzdzzh",
            "earthquake_acceleration = '" + this.sqlObj.earthquakeAcceleration +
            "' and liquefaction_ground_water_depth != '0' and task_id = '" + this.taskID + 
            "' and algorithm_type == '1' and dmsl_id = '" + this.sqlObj.dmslId + "'",'point'
          )
        }
        this.deleteIserverLayer(
        iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sand_liquefaction_polygon_evaluate_result1@fxfzdzzh",
          "earthquake_acceleration = '" + this.sqlObj.earthquakeAcceleration +
          "' and ground_water_depth = '" + this.sqlObj.liquefactionGroundWaterDepth + "' and task_id = '" + this.taskID + 
          "' and algorithm_type == '1' and dmsl_id = '" + this.sqlObj.dmslId + "'",'ploygon'
        );
      }else if(type == "3" || type == "4") {
        this.html = ''
        if(this.sqlObj.liquefactionGroundWaterDepth == '0') {
          this.deleteIserverLayer(
            iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_result_sand_liquefaction@fxfzdzzh",
            "earthquake_acceleration = '" + this.sqlObj.earthquakeAcceleration +
            "' and liquefaction_ground_water_depth = '" + this.sqlObj.liquefactionGroundWaterDepth + "' and task_id = '"
            + this.taskID + "' and algorithm_type == '2' and dmsl_id = '" + this.sqlObj.dmslId + "'",'point'
          )
        }else{
          this.deleteIserverLayer(
            iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_result_sand_liquefaction@fxfzdzzh",
            "earthquake_acceleration = '" + this.sqlObj.earthquakeAcceleration +
            "' and liquefaction_ground_water_depth != '0' and task_id = '" + this.taskID + 
            "' and algorithm_type == '2' and dmsl_id = '" + this.sqlObj.dmslId + "'",'point'
          )
        }
        this.deleteIserverLayer(
            iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sand_liquefaction_polygon_evaluate_result2@fxfzdzzh",
            "earthquake_acceleration = '" + this.sqlObj.earthquakeAcceleration +
            "' and ground_water_depth = '" + this.sqlObj.liquefactionGroundWaterDepth + "' and task_id = '" + this.taskID + 
            "' and algorithm_type == '2' and dmsl_id = '" + this.sqlObj.dmslId + "'",'ploygon'
          );
      }else if(type == "5" || type == "6"){
        url = iServerHttp() + '/iserver/services/map-dzzhTifCount/rest/maps/' + this.taskRegion
        // this.createRestMapTempLayersSet(url,'');
        this.addIserverLayerSG(url)
      }else if(type == "7"){
        url = iServerHttp() + '/iserver/services/map-dzzhTifCount/rest/maps/' + this.taskRegion
        this.addIserverLayerSG(url)
      }
    },
    addIserverLayerSG(url) {// 添加超图服务显示到地图（栅格）
      let that = this
      if (url != this.sGLayerUrl) {// 添加数据图层
        if(this.sGLayerUrl!='') {
          this.removeLayerSg(this.sGLayerUrl)
        }
        this.sGLayerUrl = url;
        let mapService = new MapService(url);//根据超图矢量瓦片图层获取图层信息
        let layer = null;
        mapService.getMapInfo(function (serviceResult) {
          if(serviceResult.result!=undefined){
            let mapJSONObj = serviceResult.result;
            let bounds = mapJSONObj.bounds;
            let left = bounds.left;
            let bottom = bounds.bottom;
            let right = bounds.right;
            let top = bounds.top;
            let origin = [left, top];//左上角
            let extent = [left, bottom, right, top];//图层范围
            layer = getRESTLayer(url,'',origin,extent,'',10)
            layer.setZIndex(6);
            //添加到REST图层数组
            let selectLayer = {
              tempLayerId: "栅格图层", //图层名称
              layerUrl: url,
            };
            that.allRestVectorLayerArray[0] = selectLayer;
            let bbox = extent.join(",");
            setTimeout(() => {
              that.map.addLayer(layer)
              that.map.getView().fit(extent, {padding: [100, 100, 100, 100]});
              that.getLayerLegend("", url, bbox); //根据url获取图层图例信息
              that.mapLoading(null)
            },200)
          }
        })
      }else { // 移除数据图层
        this.removeLayerSg(this.sGLayerUrl)
      }
    },
    removeLayerSg(layerUrl) {
      let layers = this.map.getLayers()
      let index = -1
      for(let i=0;i<layers.array_.length;i++){
        if (layers.array_[i].values_.source.options) {
          if (layerUrl == layers.array_[i].values_.source.options.url) {
            index = i
          }
        }	
      }
      this.map.removeLayer(layers.array_[index])
      this.sGLayerUrl = ''
    },
    deleteIserverLayer(layerUrl,sqltext,type) {
      let that = this
      let url = encodeURI(layerUrl + "/tempLayersSet.rjson");
      //查询
      let httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', url, true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if(obj.length == 0) {
            that.createRestMapTempLayersSet(layerUrl,sqltext,type);
          }else{
            that.deleteIservertemplent(obj,layerUrl,sqltext,type);
          }
        }
      };
    },
    deleteIservertemplent(obj,layerUrl,sqltext,type) {
      let that = this
      for(let i=0;i<obj.length;i++){
        let path = obj[i].path;
        let url = encodeURI(path);
        let xhr = new XMLHttpRequest();//第一步：建立所需的对象
        xhr.open("DELETE", url, true);//第二步：打开连接  将请求参数写在url中
        xhr.send();//第三步：发送请求  将请求参数写在URL中
        // 获取数据后的处理程序
        xhr.onreadystatechange = function(){
          let readyState = xhr.readyState;
          if (readyState == 4){
            if (i == obj.length - 1) {
              that.createRestMapTempLayersSet(layerUrl,sqltext,type);
            }
            xhr.onreadystatechange = function(){};
            xhr = null;
          }
        };
      }
    },
    createRestMapTempLayersSet(layerUrl, sqlText,type) {
      //查询REST图层信息并创建新的临时图层
      let url = encodeURI(layerUrl + "/layers.rjson");
      let that = this;
      //查询REST图层信息
      let httpRequest = new XMLHttpRequest(); //第一步：建立所需的对象
      httpRequest.open("GET", url, true); //第二步：打开连接  将请求参数写在url中
      httpRequest.send(); //第三步：发送请求  将请求参数写在URL中
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText; //获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if (obj.length > 0) {
            if (sqlText != null && sqlText != "") {
              for (let i = 0; i < obj.length; i++) {
                let layers = obj[i].subLayers.layers;
                for (let j = 0; j < layers.length; j++) {
                  layers[j].displayFilter = sqlText; //SQL查询过滤
                }
              }
            }
            that.postTempLayersSet(layerUrl, obj,type); //创建并获取超图临时图层
          }
        }
      };
    },
    postTempLayersSet(layerUrl, obj,type) {
      //创建并获取超图临时图层
      let that = this;
      let url = encodeURI(layerUrl + "/tempLayersSet.rjson");
      let entry = JSON.stringify(obj);
      let xhr = new XMLHttpRequest(); //第一步：建立所需的对象
      xhr.open("POST", url, true); //第二步：打开连接  将请求参数写在url中
      xhr.setRequestHeader(
        "Content-Type",
        "application/x-www-form-urlencoded; charset=UTF-8"
      );
      //获取数据后的处理程序
      xhr.onreadystatechange = function () {
        let readyState = xhr.readyState;
        if (readyState == 4) {
          let status = xhr.status;
          let responseText = xhr.responseText;
          let result = JSON.parse(responseText);
          if (result.succeed) {
            let layerID = result.newResourceID;
            //根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
            that.createMapRestLayer(layerUrl, layerID,type);
          }
          xhr.onreadystatechange = function () {};
          xhr = null;
        }
      };
      xhr.send(entry); //第三步：发送请求  将请求参数写在URL中
    },
    //REST图层查询
    createMapRestLayer(layerUrl, layerID,type) {
      //根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
      let that = this;
      //瓦片地图图层
      let mapService = new MapService(layerUrl); //根据超图REST图层获取图层信息
      mapService.getMapInfo(function (serviceResult) {
        if (serviceResult.result != undefined) {
          let mapJSONObj = serviceResult.result;
          let layerName = mapJSONObj.name; //图层名称
          //获取图层范围
          let bounds = mapJSONObj.bounds;
          let left = bounds.left;
          let bottom = bounds.bottom;
          let right = bounds.right;
          let top = bounds.top;
          let origin = [left, top]; //左上角
          let extent = [left, bottom, right, top]; //图层范围
          //获取超图发布的REST图层（自定义比例尺）
          let layer = getRESTLayer(
            layerUrl,
            layerID,
            origin,
            extent,
            mapJSONObj,
            17
          );
          if (that.allRestVectorLayerArray.length == 2 && that.allRestVectorLayerArray[0] != undefined) {
            that.map.removeLayer(that.allRestVectorLayerArray[0].restTileLayer);
            that.map.removeLayer(that.allRestVectorLayerArray[1].restTileLayer);
          }
          //添加到REST图层数组
          let selectLayer = {
            code: 1, //图层类型code
            name: "地貌数据", //图层名称
            layerUrl: layerUrl,
            restTileLayer: layer, //REST瓦片图层
            sqlText: "", //查询条件
            tempLayerId: layerID,//临时图层ID
          };
          if(type == 'point'){
            //添加超图图层数组
            layer.setZIndex(6);
            that.allRestVectorLayerArray[0] = selectLayer;
          }else{
            layer.setZIndex(5);
            that.allRestVectorLayerArray[1] = selectLayer;
          }
          setTimeout( () => {
            // that.map.addLayer(layer);
            detailTask({dtId: that.takId}).then(res => {
              let featureTmp = new WKT().readFeature(res.data.geom);
              Util.setMask(layer,featureTmp);
              that.map.addLayer(layer);
              //缩放到图层范围
              // that.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
              // that.mapLoading(null);
            })
            //缩放到图层范围
            if(that.taskGoem != ''){
              let feature =new WKT().readFeature(that.taskGoem)
              let extent = feature.getGeometry().getExtent();
              let allCoordinates = []
              if(extent.length==4){
                //全部经纬度--左下角
                allCoordinates.push([extent[0],extent[1]]);
                //全部经纬度--右上角
                allCoordinates.push([extent[2],extent[3]]);
              }
              that.showBoundingExtent(allCoordinates);//缩放到区域位
            }
            //that.map.getView().fit(extent, { padding: [50, 50, 50, 50] });
          },500)
          //图层范围
          let bbox = extent.join(",");
          //获取图例
          // let typeModel = that.estimateModelType;
          if(layerUrl != iServerHttp() + "/iserver/services/map-fxfzdzzh/rest/maps/dzzh_result_sand_liquefaction@fxfzdzzh") {
          //   if (typeModel == "1" || typeModel == "2") {
              that.getLayerLegend("", layerUrl, bbox); //根据url获取图层图例信息
          //   } else {
          //     that.getLayerLegend("", iServerHttp() + '/iserver/services/map-fxfzdzzh/rest/maps/dzzh_sand_liquefaction_polygon_evaluate_result2@fxfzdzzh', bbox); //根据url获取图层图例信息
          //   }
          }
        }
      });
    },
    //临时图层SQL查询更新并获取瓦片图层REST
    deleteRestMapTempLayersSet() {
      //删除超图临时图层
      let that = this;
      for(let i =0;i < this.allRestVectorLayerArray.length; i++){
        if(this.allRestVectorLayerArray[i] != undefined) {
          let layerUrl = this.allRestVectorLayerArray[i].layerUrl;
          let url = encodeURI(layerUrl + "/tempLayersSet.rjson");
          //查询
          let httpRequest = new XMLHttpRequest(); //第一步：建立所需的对象
          httpRequest.open("GET", url, true); //第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
          httpRequest.send(); //第三步：发送请求  将请求参数写在URL中
          //获取数据后的处理程序
          httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
              let json = httpRequest.responseText; //获取到json字符串，还需解析
              let obj = JSON.parse(json);
              if (obj.length > 0) {
                for (let j = 0; j < obj.length; j++) {
                  let path = obj[j].path;
                  that.deleteTempLayersSet(path,i,j); //删除超图临时图层
                }
              }
            }
          };
        }
      }
    },
    deleteTempLayersSet(url,i,j) {
      if (j == 0) {
        //删除地图加载图层
        this.map.removeLayer(this.allRestVectorLayerArray[i].restTileLayer);
      }
      // this.allRestVectorLayerArray = []
      url = encodeURI(url);
      let xhr = new XMLHttpRequest(); //第一步：建立所需的对象
      xhr.open("DELETE", url, true); //第二步：打开连接  将请求参数写在url中
      xhr.send(); //第三步：发送请求  将请求参数写在URL中
      // 获取数据后的处理程序
      xhr.onreadystatechange = function () {
        let readyState = xhr.readyState;
        if (readyState == 4) {
          let status = xhr.status;
          let responseText = xhr.responseText;
          // let result = JSON.parse(responseText);
          // if(result.succeed){
          //   //that.$message({ message: '删除临时图层成功!', type: 'success' });
          // }else{
          //   //that.$message({ message: '删除临时图层失败!', type: 'warning' });
          // }
          xhr.onreadystatechange = function () {};
          xhr = null;
        }
      };
    },
    getLayerLegend(realName, layerUrl, bbox) {
      //根据url获取图层图例信息
      let that = this;
      layerUrl += "/legend.json?bbox=" + bbox;
      layerUrl += "&returnVisibleOnly=false"; //是否只返回当前地图范围内可见要素的图例。默认为 false
      //图层图例信息查询
      let httpRequest = new XMLHttpRequest(); //第一步：建立所需的对象
      httpRequest.open("GET", layerUrl, true); //第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send(); //第三步：发送请求  将请求参数写在URL中
      /**
       * 获取数据后的处理程序
       */
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText; //获取到json字符串，还需解析
          let obj = JSON.parse(json);
          let layerLegends = obj.layerLegends;
          if (layerLegends != null && layerLegends.length > 0) {
            that.html = '';
            for (let i = 0; i < layerLegends.length; i++) {
              let layerLegend = layerLegends[i];
              //获取图层名称
              let layerName = layerLegend.layerName;
              let legends = layerLegend.legends;
              if (legends != null && legends.length > 0) {
                if (layerName.indexOf("#") != -1 && legends.length == 1) {
                  let textImgUrl =
                    iServerHttp() +
                    "/iserver/manager/static/Theme/image/LabelUniform.png";
                  //文字图层不显示图例
                  if (legends[0].url == textImgUrl) {
                    continue;
                  }
                }
                if (legends.length > 1) {
                  //多图例图层
                  that.html +=
                    '<p style="text-align: center;font-weight: bold;">' +
                    realName +
                    "</p>";
                  for (let j = 0; j < legends.length; j++) {
                    let legend = legends[j];
                    let values = legend.values;
                    if (values == null) {
                      continue;
                    }
                    let imageData = legend.imageData;
                    let contentType = legend.contentType;
                    let url = legend.url;
                    let label = legend.label;
                    let width = legend.width;
                    let height = legend.height;
                    let imgSrc = "data:image/jpeg;base64," + imageData;
                    that.html += '<p style="height: ' + height + 'px;">';
                    that.html +=
                      '<img style="width:' +
                      width +
                      "px;height:" +
                      height +
                      'px" src="' +
                      imgSrc +
                      '" />';
                    that.html +=
                      '<span style="position: relative;top: -2px;left: 10px;height: 16px;font-size: 16px;">' +
                      label +
                      "</span>";
                    that.html += "</p>";
                  }
                } else {
                  //单一图例图层
                  let legend = legends[0];
                  let values = legend.values;
                  let imageData = legend.imageData;
                  let contentType = legend.contentType;
                  let url = legend.url;
                  let label = legend.label;
                  let width = legend.width;
                  let height = legend.height;
                  let imgSrc = "data:image/jpeg;base64," + imageData;
                  that.html += '<p style="height: ' + height + 'px;">';
                  that.html +=
                    '<img style="width:' +
                    width +
                    "px;height:" +
                    height +
                    'px" src="' +
                    imgSrc +
                    '" />';
                  that.html +=
                    '<span style="position: relative;top: -2px;left: 10px;height: 16px;font-size: 16px;">' +
                    realName +
                    "</span>";
                  that.html += "</p>";
                }
              }
            }
            //图例html
            that.$emit("getLegendHtml", {
              name: realName,
              legendHtml: that.html,
              show: true,
            });
          }
        }
      };
    },
    drawTaskPonloy() {
      /*let list = this.taskRegionData;
      if (list != null && list.length > 0) {
        //清空图层
        this.evaluateResultLayer.getSource().clear();
        let allCoordinates = []; //全部经纬度
        for (let i = 1; i < list.length; i++) {
          if (list[i] == null) {
            continue;
          }
          //根据值和图例样式数组获取颜色
          let resultLevel = list[i].resultLevel; //地震滑坡密度的等级
          let backgroundColor = "rgba(0,0,0,0)";
          let legendData = this.lengendData;
          for (let j = 0; j < legendData.length; j++) {
            if (resultLevel == legendData[j].name) {
              backgroundColor = legendData[j].color;
              break;
            }
          }
          let id = list[i].id; //主键ID
          let geomText = this.getTextFormat(list[i].geomText);
          //空间数据
          let featureTmp = new WKT().readFeature(geomText);
          //样式
          let style = this.getPolyonFillStyle(backgroundColor);
          featureTmp.setStyle(style);
          //设置属性
          featureTmp.setProperties({ id: id, value: resultLevel });
          //添加人员死亡分布图（修正前）
          this.evaluateResultLayer.getSource().addFeature(featureTmp);
          //获取范围
          let extent = featureTmp.getGeometry().getExtent();
          if (extent.length == 4) {
            //全部经纬度--左下角
            allCoordinates.push([extent[0], extent[1]]);
            //全部经纬度--右上角
            allCoordinates.push([extent[2], extent[3]]);
          }
        }
        //缩放到区域位置
        this.showBoundingExtent(allCoordinates);
      }*/
    },
    getLegendArrayByData(legendSelectData) {
      //图例设置样式
      let legendArray = [];
      if (legendSelectData != null && legendSelectData.length > 0) {
        for (let i = 0; i < legendSelectData.length; i++) {
          let legendName = legendSelectData[i].name;
          let legendColor = legendSelectData[i].color;
          if (legendName.indexOf("以上") == -1) {
            if (legendName.indexOf("-") == -1) {
              //单个值
              let minLegend = Number(legendName);
              let maxLegend = minLegend;
              legendArray.push([minLegend, maxLegend, legendColor]);
            } else {
              //2个值
              let legendArr = legendName.split("-");
              let minLegend = Number(legendArr[0]);
              let maxLegend = Number(legendArr[1]);
              legendArray.push([minLegend, maxLegend, legendColor]);
            }
          } else {
            let minLegend = Number(legendName.split("以上")[0]);
            let maxLegend = null;
            legendArray.push([minLegend, maxLegend, legendColor]);
          }
        }
      }
      return legendArray;
    },
    getPolyonFillStyle(fillColor) {
      //多边形样式--不带边框
      if (fillColor == null) {
        fillColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill: new Fill({
          //填充样式
          color: fillColor,
        }),
        /*stroke:new Stroke({//描绘
            width:0.1,//宽
            color:fillColor
          })*/
      });
      return style;
    },
    getPolyonStyle(color){//多边形样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        })
      });
      return style;
    },
    getPolyonStyle(color, backgroundColor, strokeWidth) {
      //多边形样式
      if (backgroundColor == null) {
        backgroundColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill: new Fill({
          //填充样式
          color: backgroundColor,
        }),
        stroke: new Stroke({
          //描绘
          width: strokeWidth, //宽
          color: color,
        }),
      });
      return style;
    },
    //缩放到区域位置
    showBoundingExtent(coordinates) {
      console.log("缩放到区域位置");
      if (this.map != null && coordinates != null && coordinates.length > 1) {
        let extent = boundingExtent(coordinates);
        this.map.getView().fit(extent, { padding: [50, 50, 50, 50] });
      }
    },
    //根据值和图例样式数组获取颜色
    getColorByLegendArray(legendArray, value) {
      let color = "orange";
      for (let i = 0; i < legendArray.length; i++) {
        let min = legendArray[i][0];
        let max = legendArray[i][1];
        if (value >= min) {
          if (max != null) {
            if (value <= max) {
              color = legendArray[i][2];
              break;
            }
          } else {
            color = legendArray[i][2];
            break;
          }
        }
      }
      return color;
    },
    getTextFormat(str) {
      //格式化文本内容
      if (str == null || str == undefined) {
        str = "";
      }
      return str;
    },
    // 街道图与卫星图切换
    switchMap() {
      if (this.switchMapBool) {// 显示街道图
        this.switchMapBool = false
        if (this.layer1 == null) {
          this.layer1 = getTiandituVecMap()
          this.map.addLayer(this.layer1)
        }
        if (this.layer2 == null) {
          this.layer2 = getTiandituVecText()
          this.map.addLayer(this.layer2)
        }
        this.layer1.setVisible(true);
        this.layer2.setVisible(true);
        this.layer3.setVisible(false);
        this.layer4.setVisible(false);
        this.layer1.setZIndex(0);
        this.layer2.setZIndex(0);
      } else {
        this.switchMapBool = true
        if (this.layer3 == null) {
          this.layer3 = getTiandituImgMap()
          this.map.addLayer(this.layer3)
        }
        if (this.layer4 == null) {
          this.layer4 = getTiandituImgText()
          this.map.addLayer(this.layer4)
        }
        this.layer1.setVisible(false)
        this.layer2.setVisible(false)
        this.layer3.setVisible(true)
        this.layer4.setVisible(true)
        this.layer3.setZIndex(0)
        this.layer4.setZIndex(0)
      }
    },
    zoomDefaultPosition() {// 返回主界面
      this.map.updateSize();
      this.map.getView().setCenter(this.center);
      this.map.getView().setZoom(this.zoom);
      this.zoomDefaultPositionBool = true;
    },
    showHideToolsBoxDiv() {// 显示工具箱
      if (this.showHideToolsBox) {
        this.showHideToolsBox = false
        document.getElementById(this.str + '-ToolsBoxDiv').style.display = 'block'
      } else {
        this.showHideToolsBox = true
        document.getElementById(this.str + '-ToolsBoxDiv').style.display = 'none'
      }
    },
    measureToolBox() {
      if (this.showHideMeasureTool) {
        this.showHideMeasureTool = false
        document.getElementById(this.str + '-MeasureToolsDiv').style.display = 'block'
      } else {
        this.showHideMeasureTool = true
        document.getElementById(this.str + '-MeasureToolsDiv').style.display = 'none'
      }
    },
    positionToolBox() {
      if (this.showHidePositionTool) {
        this.showHidePositionTool = false
        document.getElementById(this.str + '-MousePositionDiv').style.display = 'block'
      } else {
        this.showHidePositionTool = true
        document.getElementById(this.str + '-MousePositionDiv').style.display = 'none'
      }
    },
    measureDistance() {
      if(this.source!=null){
        //地图工具箱--开启测距
        this.setMapToolBox('MeasureDistance');
        //设置样式
        this.measureDistanceBool = false;
        this.measureAreaBool = true;
        this.stopMeasureBool = true;
        this.clearMeasureBool = true;
      }
    },
    measureArea() {
      if(this.source!=null){
        //地图工具箱--开启测面
        this.setMapToolBox('MeasureArea');
        //设置样式
        this.measureAreaBool = false;
        this.measureDistanceBool = true;
        this.stopMeasureBool = true;
        this.clearMeasureBool = true;
      }
    },
    stopMeasure() {
      if(this.source!=null){
        //地图工具箱--停止测量
        this.setMapToolBox('StopMeasure');
        //设置样式
        this.stopMeasureBool = false;
        this.measureDistanceBool = true;
        this.measureAreaBool = true;
        this.clearMeasureBool = true;
      }
    },
    clearMeasure () {
      if(this.source!=null){
        //地图工具箱--清空测量结果
        this.setMapToolBox('ClearMeasure');
        //设置样式
        this.clearMeasureBool = false;
        this.measureDistanceBool = true;
        this.measureAreaBool = true;
        this.stopMeasureBool = true;
      }
    },
    clearPosition() {
      this.clearPositionBool = false;
      this.addPositionBool = true;
      //地图工具箱--清空
      this.setMapToolBox("Clear");
    },
    addPosition () {
      let that = this
      this.clearPositionBool = true
      this.addPositionBool = false
      if (that.source != null) {
        let longitude = document.getElementById(this.str+"-MousePositionLon").value;
        let latitude = document.getElementById(this.str+"-MousePositionLat").value;
        //处理经纬度
        let lonlat = this.getLonLat(longitude,latitude);
        if (lonlat != null) {
          let featureTmp = new Feature({
            geometry: new Point(lonlat)
          });
          let style = that.getPointStyle()
          featureTmp.setStyle(style)
          featureTmp.setProperties({
            type: 'position',
            longitude: longitude,
            latitude: latitude
          })
          that.source.addFeature(featureTmp)
          that.map.getView().setCenter(lonlat)
          that.map.getView().setZoom(12)
        }
      }
    },
    getPointStyle(){// 定位点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });
      return style;
    },
    getLonLat(longitude, latitude) {
      let lonlat = null
      if (longitude != null && latitude != null & longitude != '' && latitude != '') {
        let lon = Number(longitude)
        let lat = Number(latitude)
        if (lon > 0 && lon < 180 && lat > 0 && lat < 180) {
          lonlat = [ lon, lat]
        }
      }
      return lonlat
    },
    //地图工具箱
    setMapToolBox(value){
      let that = this;
      if (value === 'Clear') {//清空
        //清空
        that.source.clear();
        //停止绘制|修改|拖拽|选择
        clearInteraction();
      }else if (value === 'Point' || value === 'LineString' || value === 'Polygon' || value === 'Circle') {//开启绘制
        //点|线|面|圆绘制
        //开启绘制
        startDrawInteraction(value,false);
      }else if (value === 'FreeHandLineString' || value === 'FreeHandPolygon') {//开启绘制
        //手绘线|手绘面
        value = value.split("FreeHand")[1];
        //开启绘制
        startDrawInteraction(value,true);
      }else if (value === 'StopDraw') {//停止绘制
        //停止绘制
        stopDrawInteraction();
      }else if (value === 'Snap') {//开启捕捉
        //开启捕捉
        startSnapInteraction();
      }else if (value === 'NotSnap') {//停止捕捉
        //停止捕捉
        stopSnapInteraction();
      }else if (value === 'Modify') {//开启修改
        //开启修改
        startModifyInteraction();
      }else if (value === 'NotModify') {//停止修改
        //停止修改
        stopModifyInteraction();
        //停止选择
        stopSelectInteraction();
      }else if (value === 'Drag') {//开启拖拽
        //开启拖拽
        startDragInteraction();
      }else if (value === 'NotDrag') {//停止拖拽
        //停止拖拽
        stopDragInteraction();
      }else if (value === 'Select') {//开启选择
        //开启选择
        startSelectInteraction();
      }else if (value === 'NotSelect') {//停止选择
        //停止选择
        stopSelectInteraction();
      } else if (value === 'MeasureDistance') {//开启测距
        //开启测距
        startMeasureInteraction('LineString');
      } else if (value === 'MeasureArea') {//开启测面
        //开启测面
        startMeasureInteraction('Polygon');
      } else if (value === 'StopMeasure') {//停止测量（测距|测面）
        //停止测量
        stopMeasureInteraction();
      } else if (value === 'ClearMeasure') {//清空测量结果
        //停止测量
        stopMeasureInteraction();
        //清空测量结果
        clearMeasureResult();
      }

      //停止绘制|修改|拖拽|选择
      function clearInteraction() {
        //停止拖拽
        stopDragInteraction();
        //停止修改
        stopModifyInteraction();
        //停止选择
        stopSelectInteraction();
        //停止绘制
        stopDrawInteraction();
      }

      //停止捕捉
      function stopSnapInteraction(){
        if (that.snap) {
          that.map.removeInteraction(that.snap);
          that.snap = null;
        }
      }

      //开启捕捉
      function startSnapInteraction(){
        //停止捕捉
        stopSnapInteraction();
        //开启捕捉
        that.snap = new Snap({
          source: that.source
        });
        that.map.addInteraction(that.snap);
      }

      //停止拖拽
      function stopDragInteraction() {
        //停止拖拽
        if (that.drag) {
          that.map.removeInteraction(that.drag);
          that.drag = null;
        }
      }

      //开启拖拽
      function startDragInteraction() {
        //停止绘制
        stopDrawInteraction();
        //停止修改
        stopModifyInteraction();
        //开启选择
        startSelectInteraction();
        //停止拖拽
        stopDragInteraction();
        //开启拖拽
        that.drag = new Translate({
          features: that.select.getFeatures()
        });
        that.map.addInteraction(that.drag);
      }

      //停止修改
      function stopModifyInteraction() {
        //停止修改
        if (that.modify) {
          that.map.removeInteraction(that.modify);
          that.modify = null;
        }
      }

      //开启修改
      function startModifyInteraction() {
        //停止绘制
        stopDrawInteraction();
        //开启选择
        startSelectInteraction();
        //停止修改
        stopModifyInteraction();
        //开启修改
        // that.modify = new Modify({
        // 	features: that.select.getFeatures()
        // });
        let b = that.map.getInteractions()
        that.modify = new Modify({
          source: that.source
        });
        that.map.addInteraction(that.modify);
      }

      //停止选择
      function stopSelectInteraction() {
        //停止选择
        if (that.select) {
          that.map.removeInteraction(that.select);
          that.select = null;
        }
      }

      //开启选择
      function startSelectInteraction() {
        //停止选择
        stopSelectInteraction();
        //开启选择
        that.select = new Select({
          wrapX: false
        });
        that.map.addInteraction(that.select);
      }

      //停止绘制
      function stopDrawInteraction() {
        //停止绘制
        if (that.draw) {
          that.map.removeInteraction(that.draw);
          that.draw = null;
        }
      }

      //开启绘制
      function startDrawInteraction(type,bool) {
        //停止拖拽
        stopDragInteraction();
        //停止修改
        stopModifyInteraction();
        //停止选择
        stopSelectInteraction();
        //停止绘制
        stopDrawInteraction();
        if(bool){//手绘线|手绘面
          that.draw = new Draw({
            source: that.source,
            type: type,
            snapTolerance: 20,
            freehand: true
          });
          that.map.addInteraction(that.draw);
        }else{//点|线|面|圆绘制
          that.draw = new Draw({
            source: that.source,
            type: type,
            snapTolerance: 20
          });
          that.map.addInteraction(that.draw);
          //绘制结束时触发的事件
          that.draw.on('drawend', function(e) {
            if (e.feature && e.feature.getGeometry() instanceof CircleDraw) {
              let radius = document.getElementById('drawCircleRadius').value
              if (radius != '') {
                radius = radius * 1000
                let metersPerUnit = that.map.getView().getProjection().getMetersPerUnit();
                let circleRadius =  radius / metersPerUnit;
                e.feature.getGeometry().setRadius(circleRadius)
              }
            }
            let geometry = e.feature.getGeometry();
            //停止绘制
            stopDrawInteraction();
            let style
            //设置样式
            if (type == 'Point') {
              style = that.drawPointStyle()
            } else {
              style = that.getPolyonStyle("red");
            }
            e.feature.setStyle(style);
            //计算面积
            if (geometry instanceof Polygon || geometry instanceof CircleDraw) {
              let area = getPolygonArea(geometry);
              //清空查询行政区划列表
              that.parentdistrictList = [];
              //清空区域查询行政区划名称列表
              that.parentdistrictNameList = [];
              //清空区域查询行政区划编码列表
              that.parentdistrictCodeList = [];
              //正在查询
              that.mapLoading("正在查询，请稍候...");
              //新查询绘制区域经纬度任务地区
              that.queryDrawAreaNew(e.feature);
              /*//几何查询--省值
              that.queryProvince(e.feature);
              //几何查询--省会市值
              that.queryProCenCity(e.feature);
              //几何查询--市值
              that.queryCity(e.feature);
              //几何查询--区县值
              that.queryArea(e.feature);
              //获取多边形面内的均匀点分布数组
              let allLonLatArr = that.getPolygonExtentPoints(geometry);
              //查询绘制区域经纬度点地址
              that.queryDrawArea(e.feature,allLonLatArr);*/
              //设置属性
              e.feature.setProperties({area: area});
            }
          });
        }
      }
      //计算面积
      function getPolygonArea (geometry) {
        let area 
        let output
        let circleArea = geometry
        if (geometry instanceof CircleDraw) {
          circleArea = fromCircle(geometry)
        }
        area = getArea(circleArea, {projection: 'EPSG:4490'})
        // 这里一定要给坐标，和地图坐标保持一致，否则面积不准
        output = Math.round((area / 1000000) * 100) / 100;//平方公里
        return output;
      }

      ////////////////////////////////////////////////////////////////////测量工具箱
      //格式化距离
      function formatLength(line) {
        const length = getLength(line, {projection: 'EPSG:4490'});
        let output;
        if (length > 100) {
          output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
        } else {
          output = Math.round(length * 100) / 100 + ' ' + 'm';
        }
        return output;
      }

      //格式化面积
      function formatArea(polygon) {
        const area = getArea(polygon, {projection: 'EPSG:4490'});
        let output;
        if (area > 10000) {
          output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>';
        } else {
          output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>';
        }
        return output;
      }

      //创建新的提示tip
      function createHelpTooltip() {
        if (that.helpTooltipElement!=null) {
          that.helpTooltipElement.parentNode.removeChild(that.helpTooltipElement);
        }
        that.helpTooltipElement = document.createElement('div');
        that.helpTooltipElement.className = 'ol-tooltip hidden';
        that.helpTooltip = new Overlay({
          element: that.helpTooltipElement,
          offset: [15, 0],
          positioning: 'center-left',
        });
        that.map.addOverlay(that.helpTooltip);
      }

      //创建新的测量提示
      function createMeasureTooltip() {
        if (that.measureTooltipElement!=null) {
          that.measureTooltipElement.parentNode.removeChild(that.measureTooltipElement);
        }
        that.measureTooltipElement = document.createElement('div');
        that.measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
        that.measureTooltip = new Overlay({
          element: that.measureTooltipElement,
          offset: [0, -15],
          positioning: 'bottom-center',
          stopEvent: false,
          insertFirst: false,
        });
        that.map.addOverlay(that.measureTooltip);
      }
      //开启测量工具
      function startMeasureInteraction(type) {
        //停止测量工具
        stopMeasureInteraction();

        console.log(type);
        //开启测量工具--绘制
        that.measure = new Draw({
          source: that.measureSource,
          type: type,
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 255, 255, 0.2)',
            }),
            stroke: new Stroke({
              color: 'rgba(0, 0, 0, 0.5)',
              lineDash: [10, 10],
              width: 2,
            }),
            image: new Circle({
              radius: 5,
              stroke: new Stroke({
                color: 'rgba(0, 0, 0, 0.7)',
              }),
              fill: new Fill({
                color: 'rgba(255, 255, 255, 0.2)',
              }),
            }),
          }),
        });
        that.map.addInteraction(that.measure);

        //创建新的测量提示
        createMeasureTooltip();
        //创建新的提示tip
        createHelpTooltip();

        let listener;
        that.measure.on('drawstart', function (evt) {
          //设置sketch
          that.sketch = evt.feature;

          let tooltipCoord = evt.coordinate;

          listener = that.sketch.getGeometry().on('change', function (evt) {
            const geom = evt.target;
            let output;
            if (geom instanceof Polygon) {
              output = formatArea(geom);
              tooltipCoord = geom.getInteriorPoint().getCoordinates();
            } else if (geom instanceof LineString) {
              output = formatLength(geom);
              tooltipCoord = geom.getLastCoordinate();
            }
            that.measureTooltipElement.innerHTML = output;
            that.measureTooltip.setPosition(tooltipCoord);
          });
        });
        //完成测量绘制
        that.measure.on('drawend', function () {
          that.measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
          that.measureTooltip.setOffset([0, -7]);
          //添加到数组
          that.measureTooltipArray.push(that.helpTooltip);
          //添加到数组
          that.measureTooltipArray.push(that.measureTooltip);
          //清空sketch
          that.sketch = null;
          //清空tooltip
          that.measureTooltipElement = null;
          createMeasureTooltip();
          unByKey(listener);
        });
      }

      //停止测量工具
      function stopMeasureInteraction() {
        //停止绘制
        stopDrawInteraction();
        //停止测量工具
        if (that.measure) {
          that.map.removeInteraction(that.measure);
          that.measure = null;
          //隐藏提示tip
          that.helpTooltipElement.classList.add('hidden');
          //移除测量提示
          if(that.helpTooltip!=null){
            that.map.removeOverlay(that.helpTooltip);
          }
          if(that.measureTooltip!=null){
            that.map.removeOverlay(that.measureTooltip);
          }
        }
      }
      
      //清空测量结果
      function clearMeasureResult(){
        if(that.measureSource!=null){
          //清空测量结果
          that.measureSource.clear();
          //清空测量结果提示数组
          if(that.measureTooltipArray.length>0){
            for(let i=0;i<that.measureTooltipArray.length;i++){
              that.map.removeOverlay(that.measureTooltipArray[i]);
            }
            that.measureTooltipArray = [];
          }
        }
      }
    },
    mapLoading(msg) {
      //地图查询Loading
      if (this.mapLoadingBool) {
        this.$emit("mapLoading", msg);
      }
    },
    returnEstimateButton() {
      //返回设定地震页面
      this.$emit("returnSetPage", true);
    },
    autodivheight() {
      //自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if (document.body && document.body.clientHeight) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if (mapHeight < 480) {
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str + "-map").style.height =
        mapHeight + "px";
      console.log("窗口高度：" + winHeight + "地图高度：" + mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if (this.map) {
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
  },
};
</script>
  